package com.jack.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.jack.dto.CartDto;
import com.jack.enums.ProductStatusEnum;
import com.jack.enums.ResultEnum;
import com.jack.exception.SellException;
import com.jack.model.ProductInfo;
import com.jack.repository.ProductInfoRepository;
import com.jack.service.ProductInfoService;

@Service
public class ProductInfoServiceImpl implements ProductInfoService {

	@Autowired
	private ProductInfoRepository repository;
	
	@Override
	public ProductInfo findOne(String productId) {
		return repository.findOne(productId);
	}

	@Override
	public List<ProductInfo> findUpAll() {
		return repository.findByProductStatus(ProductStatusEnum.UP.getCode());
	}

	@Override
	public Page<ProductInfo> findAll(Pageable pagebale) {
		return repository.findAll(pagebale);
	}

	@Override
	public ProductInfo save(ProductInfo productInfo) {
		return repository.save(productInfo);
	}

	@Override
	public void increaseStock(List<CartDto> cartDto) {
		// TODO Auto-generated method stub
		
	}

	@Override
	@Transactional
	public void decreaseStock(List<CartDto> cartDtoList) {
		for (CartDto cartDto : cartDtoList) {
			ProductInfo productInfo = repository.findOne(cartDto.getProductId());
			if(productInfo == null) {
				throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
			}
			
			Integer num = productInfo.getProducStock()  - cartDto.getProductQuantity();
			if(num < 0) {
				throw new SellException(ResultEnum.PRODCT_STOCK_ERROR);
			}
			productInfo.setProducStock(num);
			repository.save(productInfo);
			
		}
	}

}
